using Microsoft.AspNetCore.Mvc;
using StudentApi.Common;
using StudentApi.Dtos;
using StudentApi.Interfaces;
using StudentApi.Models;

namespace StudentApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class StudentController : ControllerBase
{
    private readonly IRepository<Student> _StuRep;
    public StudentController(IRepository<Student> stuRep)
    {
        _StuRep = stuRep;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var list = await _StuRep.GetAllAsync();
        if (list.Count == 0)
        {
            return Ok(ApiResponse<string>.Fail(1004, "暂无学生"));
        }
        return Ok(ApiResponse<List<Student>>.Success(list));
    }

    [HttpPost]
    public async Task<IActionResult> Add(StudentDto studentDto)
    {
        var student = new Student { StuName = studentDto.StuName, Age = studentDto.Age };
        await _StuRep.AddAsync(student);
        return Ok(ApiResponse<StudentDto>.Success(studentDto));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Del(Guid id)
    {
        var student = await _StuRep.GetByIdAsync(id);
        if (student == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无此生,删除失败"));
        }
        await _StuRep.DelAsync(student);
        return Ok(ApiResponse<Student>.Success(student, "删除成功"));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Edit(Guid id, StudentDto studentDto)
    {
        var student = await _StuRep.GetByIdAsync(id);
        if (student == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无此生,修改失败"));
        }
        student.StuName = studentDto.StuName;
        student.Age = studentDto.Age;
        await _StuRep.EditAsync(student);
        return Ok(ApiResponse<StudentDto>.Success(studentDto));
    }

}